//
//  KABExhSureOrderVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/21.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABExhSureOrderVC.h"
#import "KABExhibitionTCell.h"
#import "KABModel.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABHpEditNameVC.h"
#import "KABExhOrderDetailVC.h"
#import "WXApiManager.h"

@interface KABExhSureOrderVC ()<UITableViewDelegate, UITableViewDataSource, WXApiManagerDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak,   nonatomic) IBOutlet UILabel *hPhoneLabel;
@property (strong, nonatomic) IBOutlet UIView *footerBgView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (copy, nonatomic) NSString *phoneNumber;

@property (strong, nonatomic) KABMallSubOrdBackModel *tempOrder;

@end

static NSString *const kReuseCellId = @"KABExhibitionTCell";

@implementation KABExhSureOrderVC
#pragma mark - life cycle
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActiveHandle:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"确认订单";
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initSubViews {
    [self readPhoneNumber];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerBgViewTapped:)];
    [self.headerBgView addGestureRecognizer:tapGesture];
    self.tableView.tableHeaderView = self.headerBgView;
    self.tableView.tableFooterView = self.footerBgView;
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 225.0;
//    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionHeaderHeight = 48.0;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 108.0;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.sureBtn addTarget:self action:@selector(sureBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABExhibitionTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell configViewWithExhSureOrder:self.exhItem];
    return cell;
}

#pragma mark - UITableViewDelegate
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    KABMallShoCarHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderViewId];
//    return view;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    KABMallSurOrdFooterHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kFooterViewId];
//    return view;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 6.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvPayResponse:(PayResp *)response {
    NSLog(@"微信支付返回：%d, %@, 响应类型:%d", response.errCode, response.errStr, response.type);
    NSLog(@"微信支付：财付通返回:%@", response.returnKey);

//    [self requestExhOrderQueryWithOutTradeNo:self.tempOrder.out_trade_no];
}

#pragma mark - event response
- (void)appDidBecomeActiveHandle:(NSNotification *)notification {
    if (self.tempOrder) {;
        NSLog(@"请求微信支付结果");
        // 请求微信支付结果
        [self requestExhOrderQueryWithOutTradeNo:self.tempOrder.out_trade_no];
    }
}

- (void)headerBgViewTapped:(UIGestureRecognizer *)gesture {
    KABHpEditNameVC *vc = [[KABHpEditNameVC alloc] init];
    vc.viewType = KABHpEditNameVCPhone;
    vc.completeHandle = ^(){
        [self readPhoneNumber];
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}

- (void)sureBtnTapped:(UIButton *)btn {
    if (!self.phoneNumber.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请添加常用手机号"];
        return;
    }
    
    if (self.exhItem.totalPrice == 0) {
        [self requestExhibitionFreePay];
    } else {
        [self requestExhibitionPay];
    }
}

#pragma mark - private methods
- (void)refreshWholeView {
    self.hPhoneLabel.text = self.phoneNumber;
    self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f", self.exhItem.totalPrice / 100.0];
    
    [self.tableView reloadData];
}

- (void)readPhoneNumber {
    self.phoneNumber = [[NSUserDefaults standardUserDefaults] objectForKey:KABGlobalUserDefaultGeneralPhoneNO];
}

- (void)jumpToOrderDetailWithOrderId:(NSString *)orderId {
    // 清空临时数据
    self.tempOrder = nil;
    // 跳转
    KABExhOrderDetailVC *vc = [[KABExhOrderDetailVC alloc] init];
    vc.order_id = orderId;
    
    NSMutableArray *mArray = [self.navigationController.viewControllers mutableCopy];
    [mArray replaceObjectAtIndex:(mArray.count - 1) withObject:vc];
    [self.navigationController setViewControllers:mArray animated:YES];
    
}

#pragma mark - network request
#pragma mark - getters and setters
- (void)requestExhibitionFreePay {
    // 必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 购买门票请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"exhibition_id" : @(self.exhItem.exhibition_id),
                           @"phone_number" : self.phoneNumber,
                           @"ticket_id" : @(self.exhItem.ticket_id),
                           @"number" : @(self.exhItem.number)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiExhibitionFreeBuy] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"提交订单返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSString *orderId = responseObject[KABGlobalJsonKeyResult];
            MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"购买成功"];
            temp.completionBlock = ^{
                [self jumpToOrderDetailWithOrderId:orderId];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"提交订单失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestExhibitionPay {
    // 必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 购买门票请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"exhibition_id" : @(self.exhItem.exhibition_id),
                           @"phone_number" : self.phoneNumber,
                           @"ticket_id" : @(self.exhItem.ticket_id),
                           @"number" : @(self.exhItem.number)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiExhibitionBuy] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"提交订单返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.tempOrder = [KABMallSubOrdBackModel yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self callWx:self.tempOrder.wx_pay];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"提交订单失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)callWx:(KABMallWxPayPars *)wxPay {
    if (!wxPay) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"微信支付参数错误"];
        return;
    }
    
    // 置位代理
    [WXApiManager sharedManager].delegate = self;
    
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = wxPay.partnerId;
    request.prepayId= wxPay.prepayId;
    request.package = wxPay.package;
    request.nonceStr= wxPay.nonceStr;
    request.timeStamp= wxPay.timeStamp;
    request.sign= wxPay.sign;
    NSLog(@"请求参数:\n partnerId = %@ \n prepayId = %@ \n package = %@ \n nonceStr = %@ \n timeStamp = %zd \n sign = %@ ", request.partnerId, request.prepayId, request.package, request.nonceStr, request.timeStamp, request.sign);
    [WXApi sendReq:request];
}

- (void)requestExhOrderQueryWithOutTradeNo:(NSString *)out_trade_no {
    // 查询购买结果必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    if (!out_trade_no.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"订单号错误"];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"out_trade_no" : out_trade_no};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiExhibitionOrderQuery] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"查询结果返回：%@", responseObject);
        [hud hideAnimated:NO];
        NSString *str = responseObject[KABGlobalJsonKeyMsg];
        BOOL paySuc = NO;
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSDictionary *dic = responseObject[KABGlobalJsonKeyResult];
            str = ([dic[@"result_code"] integerValue] == 1) ? @"支付成功" : @"支付失败";
            paySuc = ([dic[@"result_code"] integerValue] == 1) ? YES : NO;
        }
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:str];
        temp.completionBlock = ^(){
            if (paySuc) {
                [self jumpToOrderDetailWithOrderId:self.tempOrder.order_id];
            }
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"查询结果失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//        temp.completionBlock = ^(){
//            [self jumpToOrderDetailWithOrderId:self.tempOrder.order_id];
//        };
    }];
}

@end
